import 'dart:convert';
import 'dart:developer';

import 'package:flutter/services.dart';
import 'package:im_base/public/global/custom_bean.dart';
import 'package:im_base/public/global/im_keys.dart';
import 'package:tencent_im_sdk_plugin/enum/group_change_info_type.dart';
import 'package:tencent_im_sdk_plugin/enum/group_tips_elem_type.dart';
import 'package:tencent_im_sdk_plugin/enum/message_elem_type.dart';
import 'package:tencent_im_sdk_plugin/models/v2_tim_custom_elem.dart';
import 'package:tencent_im_sdk_plugin/models/v2_tim_message.dart';

void copyString(String content) {
  Clipboard.setData(ClipboardData(text: content));
}

///扩展String判断空方法,增加对null的判断
extension StringExt on String? {
  bool isNullEmpty() {
    return this == null || this!.isEmpty;
  }
}

String getSize(int? size) {
  if (size == null) {
    return '';
  }
  if (size < 1000 * 100) {
    return (size / 1000).toStringAsFixed(2) + 'k';
  }
  if (size >= 1000 * 100) {
    return (size / 1000 / 1000).toStringAsFixed(2) + 'M';
  }
  return '';
}

///最后一条消息展示内容
String? getLastMsg(V2TimMessage? lastMsg) {
  bool isGroup = lastMsg != null && (lastMsg.groupID ?? '').isNotEmpty;
  return lastMsg != null
      ? lastMsg.status == 6
      ? lastMsg.isSelf!
      ? "你撤回了一条消息"
      : "${lastMsg.nickName} 撤回了一条消息"
      : lastMsg.elemType == MessageElemType.V2TIM_ELEM_TYPE_TEXT
      ? lastMsg.textElem == null
      ? ''
      : '${isGroup ? '${lastMsg.nickName}: ' : ''}${lastMsg.textElem!.text}'
      : lastMsg.elemType == MessageElemType.V2TIM_ELEM_TYPE_FACE
      ? lastMsg.faceElem == null
      ? '${isGroup ? '${lastMsg.nickName}:' : ''}【表情】'
      : '${isGroup ? '${lastMsg.nickName}:' : ''}【${lastMsg.faceElem!.data}】'
      : lastMsg.elemType == MessageElemType.V2TIM_ELEM_TYPE_FILE
      ? '${isGroup ? '${lastMsg.nickName}:' : ''}【文件】'
      : lastMsg.elemType ==
      MessageElemType.V2TIM_ELEM_TYPE_IMAGE
      ? '${isGroup ? '${lastMsg.nickName}:' : ''}【图片】'
      : lastMsg.elemType ==
      MessageElemType.V2TIM_ELEM_TYPE_CUSTOM
      ? customMsg(lastMsg.customElem)
      : lastMsg.elemType ==
      MessageElemType.V2TIM_ELEM_TYPE_GROUP_TIPS
      ? '${isGroup ? '${lastMsg.nickName}:' : ''}【群聊消息】'
      : lastMsg.elemType ==
      MessageElemType
          .V2TIM_ELEM_TYPE_LOCATION
      ? '${isGroup ? '${lastMsg.nickName}:' : ''}【位置】'
      : lastMsg.elemType ==
      MessageElemType
          .V2TIM_ELEM_TYPE_SOUND
      ? '${isGroup ? '${lastMsg.nickName}:' : ''}【语音】'
      : lastMsg.elemType ==
      MessageElemType
          .V2TIM_ELEM_TYPE_VIDEO
      ? '${isGroup ? '${lastMsg.nickName}:' : ''}【视频】'
      : ''
      : "";
}

///系统消息
String notifyMsg(V2TimMessage? message) {
  String notify = '';
  if (message != null) {
    if (message.status == 6) {
      notify =
      message.isSelf ?? false ? "你撤回了一条消息" : "${message.nickName} 撤回了一条消息";
    } else if (message.elemType == MessageElemType.V2TIM_ELEM_TYPE_GROUP_TIPS &&
        message.groupTipsElem != null) {
      ///群体提示
      var tipsElem = message.groupTipsElem!;

      ///操作人
      var opName = tipsElem.opMember.userID == 'admin' ? '超级管理员' : tipsElem
          .opMember.nickName ?? tipsElem.opMember.nameCard ??
          tipsElem.opMember.userID;

      ///被操作人
      String name = '';
      if (tipsElem.memberList != null) {
        if (tipsElem.memberList!.length == 1) {
          name = tipsElem.memberList![0]?.nickName ??
              tipsElem.memberList![0]?.nameCard ??
              tipsElem.memberList![0]?.userID ?? '';
        } else if (tipsElem.memberList!.length < 4) {
          tipsElem.memberList!.forEach((element) {
            name += ',${tipsElem.memberList![0]?.nickName ??
                tipsElem.memberList![0]?.nameCard ??
                tipsElem.memberList![0]?.userID}';
          });
          if (name.isNotEmpty && name.length > 1) {
            name = name.substring(1);
          }
        } else if (tipsElem.memberList!.length > 3) {
          tipsElem.memberList!.sublist(0, 3).forEach((element) {
            name += ',${tipsElem.memberList![0]?.nickName ??
                tipsElem.memberList![0]?.nameCard ??
                tipsElem.memberList![0]?.userID}';
          });
          name = name.substring(1);
          name = '$name 等${tipsElem.memberList!.length}人';
        }
      }
      switch (tipsElem.type) {
        case GroupTipsElemType.V2TIM_GROUP_TIPS_TYPE_CANCEL_ADMIN:

        ///取消管理员权限
          notify = '$opName 取消了 $name 的管理员权限';
          break;
        case GroupTipsElemType.V2TIM_GROUP_TIPS_TYPE_GROUP_INFO_CHANGE:
          if (tipsElem.groupChangeInfoList != null &&
              tipsElem.groupChangeInfoList!.isNotEmpty) {
            var changeInfo = tipsElem.groupChangeInfoList![0]!;
            if (changeInfo.type ==
                GroupChangeInfoType.V2TIM_GROUP_INFO_CHANGE_TYPE_NAME) {
              notify = '$opName 修改群名称为 ${changeInfo.value}';
            }
            if (changeInfo.type ==
                GroupChangeInfoType.V2TIM_GROUP_INFO_CHANGE_TYPE_INTRODUCTION) {
              notify = '$opName 修改群简介称为 ${changeInfo.value}';
            }
            if (changeInfo.type ==
                GroupChangeInfoType.V2TIM_GROUP_INFO_CHANGE_TYPE_OWNER) {
              notify = '$opName 将 ${changeInfo.value} 设为群主';
            }
          } else {
            notify = '$opName 修改了群信息';
          }
          break;
        case GroupTipsElemType.V2TIM_GROUP_TIPS_TYPE_INVITE:
          notify = '$opName 邀请$name 加入群聊';
          break;
        case GroupTipsElemType.V2TIM_GROUP_TIPS_TYPE_JOIN:
          notify = '$name 加入群聊';
          break;
        case GroupTipsElemType.V2TIM_GROUP_TIPS_TYPE_KICKED:
          notify = '$opName 将 $name 踢出了群聊';
          break;
        case GroupTipsElemType.V2TIM_GROUP_TIPS_TYPE_MEMBER_INFO_CHANGE:
          break;
        case GroupTipsElemType.V2TIM_GROUP_TIPS_TYPE_QUIT:
          notify = '$name 退出了群聊';
          break;
        case GroupTipsElemType.V2TIM_GROUP_TIPS_TYPE_SET_ADMIN:
          notify = '$opName 将 $name 设置为群管理';
          break;
      }
    }
  }
  return notify;
}

///自定义消息显示文字信息
///其余的只展示 问诊消息
String customMsg(V2TimCustomElem? customElem) {
  var data = (customElem?.data ?? '').isEmpty
      ? customElem?.extension ?? ''
      : customElem?.data ?? '';
  if (!data.contains('\'') && !data.contains('\"')) {
    data = data
        .replaceAll('{', '{"')
        .replaceAll(':', '":"')
        .replaceAll(',', '","')
        .replaceAll('}', '"}')
        .replaceAll(' ', '')
        .trim();
  }
  try {
    CustomBean bean = CustomBean.fromMap(jsonDecode(data));
    switch (bean.msg) {
      case IMKeys.TYPE_RECOMMEND:

      ///群推荐
        return '群推荐';
      case IMKeys.TYPE_DEL_RECIPE:

      ///作废处方
        return '医生作废了处方';

      case IMKeys.TYPE_DEL_CHECK:

      ///作废检查单
        return '医生作废了检验检查单';

      case IMKeys.PAT_OVER_WORD_INQUIRY:

      ///患者结束图文会诊
        return '患者结束图文问诊';

      case IMKeys.DOC_OVER_WORD_INQUIRY:
        return '医生结束图文问诊';

      case IMKeys.END_VIDEO_INQUIRY:

      ///结束视频会诊
        return '医生结束视频问诊';

      case IMKeys.PAT_OVER_VIDEO_INQUIRY:

      ///患者结束视频会诊
        return '患者结束视频问诊';

      case IMKeys.ANSWERED_ON_OTHER_DEVICE:

      ///在其他设备接听
        return '患者已接听';
      case IMKeys.CHECK_IMAGES:

      ///患者发送图片信息
        return '患者上传了问诊图片';

      case IMKeys.INQUIRY_IMAGES:

      ///收到患者传来的图片
        return '收到患者上传的图片';

    ///医生填写诊断信息
      case IMKeys.DIAGNOSIS:
        return '医生填写了诊断信息';

    ///医生填写主诉
      case IMKeys.MAIN_SUIT:
        return '医生填写了主诉信息';

    ///医生填写既往史
      case IMKeys.JWS:
        return '医生填写了既往史';

    ///医生填写现病史
      case IMKeys.XBS:
        return '医生填写了现病史';

    ///医生开具处方
      case IMKeys.RECIPE:
        return '医生开具了处方笺';

    ///医生开具健康指导
      case IMKeys.HEALTH_GUIDE:
        return '医生开具了健康指导';

    ///医生开具住院建议
      case IMKeys.HOSPITAL_ADVICE:
        return '医生开具了住院建议';

    ///医生开具检验检查单
      case IMKeys.CHECK:
        return '医生开具了检验检查单';

    ///医生填写过敏史
      case IMKeys.ALLERGY_HISTORY:
        return '医生填写了过敏史';
      case IMKeys.NO_RESPONSE_END:
        return '对方无应答';
      case IMKeys.TYPE_CASE:
        return '病历信息';
      default:
        return '自定义消息';
    }
  } on Exception catch (e) {
    log(e.toString());
  }

  return '问诊消息';
}

///会话列表中时间格式化
String formatTime(int timeStamp) {
  int timestamp = timeStamp * 1000;
  DateTime time = DateTime.fromMillisecondsSinceEpoch(timestamp);
  DateTime now = DateTime.now();

  if (now.day == time.day) {
    return "${time.hour.toString().padLeft(2, '0')}:${time.minute.toString()
        .padLeft(2, '0')}:${time.second.toString().padLeft(2, '0')}";
  } else if (now.day - time.day == 1) {
    return '昨天${time.hour.toString().padLeft(2, '0')}:${time.minute.toString()
        .padLeft(2, '0')}';
  } else {
    return "${time.year}/${time.month.toString().padLeft(2, '0')}/${time.day
        .toString().padLeft(2, '0')} ${time.hour.toString().padLeft(
        2, '0')}:${time.minute.toString().padLeft(2, '0')}";
  }
}

///计算消息之间的时间差是否在半个小时
///[timeStamp] 上一条消息的时间
///[currentTime] 当前消息的时间,如果计算的为首条消息,则为当前时间
///先判断是否为今年,是则比较是否为当月,否则直接展示时间
///如果为当月判断是否为当天,是当天只展示时间,是昨天展示昨天+时间,否则展示完整日期
String? showDate(int timeStamp, int currentTime) {
  timeStamp = timeStamp * 1000;
  String? showDate;
  DateTime lastDate = DateTime.fromMillisecondsSinceEpoch(timeStamp);
  DateTime now = DateTime.now();
  if (now.year == lastDate.year) {
    ///同一年,判断是否为同一月
    if (now.month == lastDate.month) {
      ///同一个月判断是否为同一天
      if (now.day == lastDate.day) {
        ///如果为同一天,则只展示时分
        if ((currentTime - timeStamp).abs() >= 30 * 60 * 1000 &&
            (now.millisecondsSinceEpoch - timeStamp) >= 20 * 60 * 1000) {
          ///只有当两条消息之间的时间间隔大于30分钟,并且最新一条消息与当前时间差大于20分钟才会展示
          showDate =
          '${lastDate.hour.toString().padLeft(2, '0')}:${lastDate.minute
              .toString().padLeft(2, '0')}';
        }
      } else if (now.millisecondsSinceEpoch - timeStamp < 24 * 60 * 60 * 1000) {
        ///如果不是当天,判断时间差是否小于24小时,小于展示昨天
        if ((currentTime - timeStamp).abs() >= 30 * 60 * 1000) {
          showDate =
          '昨天 ${lastDate.hour.toString().padLeft(2, '0')}:${lastDate.minute
              .toString().padLeft(2, '0')}';
        }
      } else {
        ///不是同一天并且时间差大于24小时,展示月日时分
        if ((currentTime - timeStamp).abs() >= 30 * 60 * 1000) {
          showDate =
          '${lastDate.month.toString().padLeft(2, '0')}月${lastDate.day
              .toString().padLeft(2, '0')}日 ${lastDate.hour.toString().padLeft(
              2, '0')}:${lastDate.minute.toString().padLeft(2, '0')}';
        }
      }
    } else {
      ///如果不是当前月,直接展示完整时间
      if ((currentTime - timeStamp).abs() >= 30 * 60 * 1000) {
        showDate =
        '${lastDate.year}年${lastDate.month.toString().padLeft(
            2, '0')}月${lastDate.day.toString().padLeft(2, '0')}日 ${lastDate.hour
            .toString().padLeft(2, '0')}:${lastDate.minute.toString().padLeft(
            2, '0')}';
      }
    }
  } else {
    ///如果不是今年的直接展示完整时间
    if ((currentTime - timeStamp).abs() >= 30 * 60 * 1000) {
      showDate =
      '${lastDate.year}年${lastDate.month.toString().padLeft(2, '0')}月${lastDate
          .day.toString().padLeft(2, '0')}日 ${lastDate.hour.toString().padLeft(
          2, '0')}:${lastDate.minute.toString().padLeft(2, '0')}';
    }
  }
  return showDate;
}

///从android 和ios接收的json数据格式不对,这里需要进行转换
dynamic formatJson(jsonSrc) {
  return json.decode(json.encode(jsonSrc));
}
